package com.xxx.video.main.activitys;

import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.xxx.player.gsyvideoplayer.GSYVideoManager;
import com.xxx.player.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.xxx.player.gsyvideoplayer.listener.BaseVideoAllCallBackImp;
import com.xxx.player.gsyvideoplayer.utils.OrientationUtils;
import com.xxx.player.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.xxx.video.R;
import com.xxx.video.commen.activitys.BaseActivity;
import com.xxx.video.commen.configs.Constant;
import com.xxx.video.commen.configs.UserManager;
import com.xxx.video.commen.dbs.beans.DownloadHistoryBean;
import com.xxx.video.commen.dbs.utils.DbUtils;
import com.xxx.video.commen.events.CommentSuccessEvent;
import com.xxx.video.commen.utils.AppBarLayoutStateChangeListener;
import com.xxx.video.commen.utils.DownloadUtils;
import com.xxx.video.commen.utils.ResourcesUtils;
import com.xxx.video.commen.utils.SPUtil;
import com.xxx.video.commen.utils.ViewPager2Utils;
import com.xxx.video.download.StatusUtil;
import com.xxx.video.login.activitys.LoginActivity;
import com.xxx.video.main.adapters.VideoDetailsPagerAdapter;
import com.xxx.video.main.beans.VideoDetailsBean;
import com.xxx.video.main.presenters.IVideoDetailsView;
import com.xxx.video.main.presenters.VideoDetailsPresenter;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;


public class VideoDetailsActivity extends BaseActivity<VideoDetailsPresenter> implements IVideoDetailsView {
    protected OrientationUtils orientationUtils;
    protected boolean isPlay;

    protected boolean isPause;

    @BindView(R.id.pv_video_details)
    StandardGSYVideoPlayer pvVideoDetails;
    @BindView(R.id.tl_video_details)
    TabLayout tlVideoDetails;
    @BindView(R.id.vp_video_details)
    ViewPager2 vpVideoDetails;

    @BindView(R.id.iv_video_details_actionbar_left_icon)
    ImageView ivActionbarLeftIcon;
    @BindView(R.id.tv_actionbar_left_tile)
    TextView tvActionbarLeftTile;
    @BindView(R.id.cl_video_details_toolbar)
    ConstraintLayout clVideoDetailsToolbar;
    @BindView(R.id.abl_video_details)
    AppBarLayout ablVideoDetails;
    @BindView(R.id.et_video_details_bottom_comment)
    EditText etVideoDetailsBottomComment;
    @BindView(R.id.tv_video_details_bottom_comment_send)
    TextView tvVideoDetailsBottomCommentSend;
    @BindView(R.id.cl_video_details_bottom_comment)
    ConstraintLayout clVideoDetailsBottomComment;

    /**
     * video Id
     */
    private String mVideoId;
    /**
     * is download
     */
    private boolean isDownload;
    /**
     * start play time
     */
    private long startTime;
    /**
     * is set 4g
     */
    private boolean mIsSet4G;

    @Override
    public int getContentLayout() {
        return R.layout.activity_video_details;
    }

    @Override
    protected VideoDetailsPresenter createPresenter() {
        return new VideoDetailsPresenter(this, this);
    }

    @Override
    public void initData(Bundle extras) {
        if (extras != null) {
            mVideoId = extras.getString("Id");
            isDownload = extras.getBoolean("IsDownload");
        }
        mIsSet4G = SPUtil.getBoolean(Constant.isSet4G, false);

        initTabLayout();
        if (UserManager.getInstance().isLogin()) {
            getPresenter().browse(mVideoId);
        }
        if (isDownload) {
            DownloadHistoryBean downloadHistoryBean = DbUtils.getInstance().getDownloadHistoryBean(mVideoId);
            StatusUtil.Status status = DownloadUtils.getInstance().getStatus(ResourcesUtils.getInstance().getDownloadPath(downloadHistoryBean.fVideo));
            if (status == StatusUtil.Status.COMPLETED) {
                showLayoutStatus(1);
                initVideo(downloadHistoryBean.fTitle, Constant.DOWNLOAD_VIDEO_PATH + DownloadUtils.getInstance().getFileName(ResourcesUtils.getInstance().getDownloadPath(downloadHistoryBean.fVideo)));
            } else {
                getPresenter().getContentInfo(mVideoId);
            }
        } else {
            getPresenter().getContentInfo(mVideoId);
        }
    }

    /**
     * @param fTitle title
     */
    public void initVideo(String fTitle, String url) {
        orientationUtils = new OrientationUtils(this, getGSYVideoPlayer(), null);
        orientationUtils.setEnable(false);
        if (getGSYVideoPlayer().getFullscreenButton() != null) {
            getGSYVideoPlayer().getFullscreenButton().setOnClickListener(v -> showFull());
        }
        getGSYVideoOptionBuilder(fTitle, url).setVideoAllCallBack(new BaseVideoAllCallBackImp() {
            @Override
            public void onPrepared(String url, Object... objects) {

                if (orientationUtils == null) {
                    throw new NullPointerException("initVideo() or initVideoBuilderMode() first");
                }
                orientationUtils.setEnable(true);
                isPlay = true;
                startTime = System.currentTimeMillis();
                /*
                 * play
                 */
                if (UserManager.getInstance().isLogin()) {
                    getPresenter().play(mVideoId, 0);
                }
            }


            @Override
            public void onQuitFullscreen(String url, Object... objects) {
                if (orientationUtils != null) {
                    orientationUtils.backToProtVideo();
                }
            }
        })
                .build(getGSYVideoPlayer());
    }

    public void showFull() {
        if (orientationUtils.getIsLand() != 1) {
            orientationUtils.resolveByClick();
        }
        getGSYVideoPlayer().startWindowFullscreen(VideoDetailsActivity.this, true, true);

    }

    public StandardGSYVideoPlayer getGSYVideoPlayer() {
        return pvVideoDetails;
    }

    public GSYVideoOptionBuilder getGSYVideoOptionBuilder(String title, String url) {
        ImageView imageView = new ImageView(this);
        return new GSYVideoOptionBuilder()
                .setThumbImageView(imageView)
                .setUrl(url)
                .setCacheWithPlay(true)
                .setVideoTitle(title)
                .setIsTouchWiget(true)
                .setRotateViewAuto(false)
                .setLockLand(false)
                .setShowFullAnimation(false)
                .setNeedLockFull(true)
                .setNeedShowWifiTip(!mIsSet4G)
                .setSeekRatio(1);
    }

    @Override
    public void onBackPressed() {
        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }


    @Override
    protected void onPause() {
        super.onPause();
        getGSYVideoPlayer().getCurrentPlayer().onVideoPause();
        if (orientationUtils != null) {
            orientationUtils.setIsPause(true);
        }
        isPause = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        getGSYVideoPlayer().getCurrentPlayer().onVideoResume();
        if (orientationUtils != null) {
            orientationUtils.setIsPause(false);
        }
        isPause = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isPlay) {
            getPresenter().play(mVideoId, startTime);
            try {
                getGSYVideoPlayer().getCurrentPlayer().release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (orientationUtils != null) {
            orientationUtils.releaseListener();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (isPlay && !isPause) {
            getGSYVideoPlayer().onConfigurationChanged(this, newConfig, orientationUtils, true, true);
        }
    }

    @Override
    public void showRootLayoutStatus(int status) {
        showLayoutStatus(status);
    }

    @Override
    public void initTabLayout() {
        ViewPager2Utils.getInstance().reduceDragSensitivity(vpVideoDetails);
        VideoDetailsPagerAdapter videoDetailsPagerAdapter = new VideoDetailsPagerAdapter(this, mVideoId);
        vpVideoDetails.setAdapter(videoDetailsPagerAdapter);
        new TabLayoutMediator(tlVideoDetails, vpVideoDetails, (tab, position) -> {
            switch (position) {
                case 0:
                    tab.setText(R.string.tb_video_details_first);
                    break;
                default:
                    tab.setText(R.string.tb_video_details_second);
                    break;
            }

        }).attach();
        tlVideoDetails.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 1) {
                    clVideoDetailsBottomComment.setVisibility(View.VISIBLE);
                } else {
                    clVideoDetailsBottomComment.setVisibility(View.GONE);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        ablVideoDetails.addOnOffsetChangedListener(new AppBarLayoutStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {
                    clVideoDetailsToolbar.setVisibility(View.GONE);
                } else if (state == State.COLLAPSED) {
                    clVideoDetailsToolbar.setVisibility(View.VISIBLE);
                } else {
                    clVideoDetailsToolbar.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void initData2View(VideoDetailsBean successOb) {
        if (successOb.contentInfo == null) {
            showLayoutStatus(3);
        } else {
            showLayoutStatus(1);
            initVideo(successOb.contentInfo.fTitle, ResourcesUtils.getInstance().getImagePath(successOb.contentInfo.fVideo));
        }
    }

    @Override
    public void startLoginActivity() {
        intent2Activity(LoginActivity.class);
    }

    @Override
    public void addCommentSuccess() {
        hideKeyBoard();
        CommentSuccessEvent commentSuccessEvent = new CommentSuccessEvent.Builder().comment(getComment()).build();
        EventBus.getDefault().post(commentSuccessEvent);
    }

    @Override
    public String getComment() {
        return etVideoDetailsBottomComment.getText().toString().trim();
    }

    @Override
    public void clearComment() {
        etVideoDetailsBottomComment.setText("");
    }

    @OnClick({R.id.iv_video_details_actionbar_left_icon, R.id.back, R.id.tv_video_details_bottom_comment_send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
            case R.id.iv_video_details_actionbar_left_icon:
                onBackPressed();
                break;
            case R.id.tv_video_details_bottom_comment_send:
                if (!UserManager.getInstance().isLogin()) {
                    startLoginActivity();
                    return;
                }
                getPresenter().comment(mVideoId);
                break;
            default:
                break;
        }
    }
}
